import 'package:flutter/widgets.dart';
import 'package:mvvm_provider/base/base_state.dart';
import 'package:mvvm_provider/base/base_view_model.dart';
import 'package:mvvm_provider/base/select_plus_data.dart';
import 'package:provider/provider.dart';

class SelectorWidget<T extends BaseViewModel<S>, S extends BaseState, A>
    extends StatelessWidget {
  final Widget Function(BuildContext context, dynamic value, Widget? child) builder;
  final Widget? child;

  /// 判断是否需要刷新的字段 特别需要指明的是selector的结果，必须是不可变的对象。 如果同一个对象，只是改变对象属性，那shouldRebuild的两个值永远是相等的。
  final SelectorPlusData Function(BuildContext context, S state)? plusDataSelector;
  final A Function(BuildContext context, S state)? selector;

  const SelectorWidget(
      {super.key, required this.builder, this.child, this.plusDataSelector, this.selector});

  @override
  Widget build(BuildContext context) {
    if (plusDataSelector != null) {
      return Selector<T, SelectorPlusData>(
        builder: builder,
        selector: (context, value) => plusDataSelector!(context, value.state),
        shouldRebuild: (pre, next) => next.shouldRebuild(),
        child: child,
      );
    }
    return Selector<T, A>(
      builder: builder,
      selector: (context, value) => selector!(context, value.state),
      shouldRebuild: (pre, next) => pre != next,
      child: child,
    );
  }
}
